import React from 'react'
import ReactDOM from 'react-dom'

import './base.css'

class App extends React.Component {
  state = {
    list: [
      { id: 1, username: '叶树森', content: '冲冲冲冲冲冲冲冲冲冲' },
      { id: 2, username: '叶树森2', content: '冲冲冲冲冲冲冲冲冲冲' },
      { id: 3, username: '叶树森3', content: '冲冲冲冲冲冲冲冲冲冲' },
    ],
    username: '',
    content: '',
  }
  handDetele = (id) => {
    this.setState({ list: this.state.list.filter((item) => item.id !== id) })
  }
  handClear = () => {
    this.setState({ list: [] })
  }
  handChange = (e) => {
    this.setState({
      [e.target.name]: e.target.value,
    })
  }
  handlePublish = (e) => {
    e.preventDefault()
    // console
    // this.state.username
    const { username, content } = this.state
    console.log(username, content)
    if (username.trim() === '' || content.trim() === '') return alert('不能为空')
    this.setState({
      list: [...this.state.list, { id: Date.now(), username, content }],
      username: '',
      content: '',
    })
  }
  render() {
    return (
      <>
        <div className='app'>
          <div>
            {/* 移动端推荐写法 */}
            <form onSubmit={this.handlePublish}>
              <input onChange={this.handChange} value={this.state.username} type='text' className='user' placeholder='请输入评论人' name='username' />
              <br />
              <textarea onChange={this.handChange} value={this.state.content} name='content' id='' cols='30' rows='10' placeholder='请输入评论'></textarea>
              <br />
              <button>发表评论</button>
              <button type='button' onClick={this.handClear}>
                清空评论
              </button>
            </form>
          </div>
          {this.state.list.length === 0 ? (
            <div>暂无评论</div>
          ) : (
            <ul>
              {this.state.list.map((item) => (
                <CommentItem item={item} key={item.id} handDetele={this.handDetele} />
              ))}
            </ul>
          )}
        </div>
      </>
    )
  }
}
// 函数组件
function CommentItem({ item, handDetele }) {
  return (
    <li key={item.id}>
      <h3>评论人：{item.username}</h3>
      <p>评论内容：{item.content}</p>
      <button onClick={() => handDetele(item.id)}>删除</button>
    </li>
  )
}
// class CommentItem extends React.Component {
//   render() {
//     const { item, handDetele } = this.props
//     return (
//       <li key={item.id}>
//         <h3>评论人：{item.username}</h3>
//         <p>评论内容：{item.content}</p>
//         <button onClick={() => handDetele(item.id)}>删除</button>
//       </li>
//     )
//   }
// }
ReactDOM.render(<App />, document.getElementById('root'))

// first = (second) => {third}  met缩写
